package es.masterd.e8_2;


import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class GpsAlarmActivity extends Activity implements LocationListener {
    private static final float MIN_DISTANCIA = 1;
	private TextView alarma;
	private Location destino;
	private LocationManager locationManager;
	
	
	// http://maps.google.es/maps?f=q&source=s_q&hl=es&geocode=&q=el+pilar,+zaragoza,+espa%C3%B1a&sll=40.396764,-3.713379&sspn=9.334598,14.128418&ie=UTF8&hq=&hnear=Bas%C3%ADlica+de+Nuestra+Se%C3%B1ora+del+Pilar,+Plaza+de+Nuestra+Se%C3%B1ora+del+Pilar,+19,+50003+Zaragoza,+Arag%C3%B3n&ll=41.656938,-0.878606&spn=0.004473,0.006899&t=h&z=17&iwloc=A

	/** Called when the activity is first created. */
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Destino
        //destino = new Location("Plaza del Pilar");
        destino = new Location("CASA");
        destino.setLatitude(40.41208684);
        //destino.setLatitude(41.65657735);
        //destino.setLongitude(-0.87836981);
        destino.setLongitude(-3.6634683);
      
        // Alarma
        alarma = (TextView) findViewById(R.id.alarma);
        
        // "Escuchamos al GPS"
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }
    
    
    protected void onStart() {
    	super.onStart();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
    
    
    protected void onStop() {
		locationManager.removeUpdates(this);
		super.onStop();
    }

	
	public void onLocationChanged(Location nuevaLoc) {
		float metros = nuevaLoc.distanceTo(destino);
		
		String t = nuevaLoc.getLatitude()+","+nuevaLoc.getLongitude()+"\n";
		t+= destino.getLatitude()+","+destino.getLongitude()+"\n";
		t+= metros+"m";
		
		alarma.setText(t);
		
		Log.d("GPS alarma", "Distancia: " + metros +"m.");
		if(metros > MIN_DISTANCIA) {
			alarma.setEnabled(false);
		} else {
			alarma.setEnabled(true);
		}
	}

	
	public void onProviderDisabled(String arg0) {
		 Auto-generated method stub
		
	}

	
	public void onProviderEnabled(String arg0) {
		 Auto-generated method stub
		
	}

	
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		 Auto-generated method stub
		
	}
    
    
    
   
}